<template>
  <div class="x-image">
    <img :src="imgUrl" @error="errorImg" :style="{width:imgWidth,height:imgHeight}" />
  </div>
</template>
<script>
  import {
    getImg as getLoadImage
  } from '@/api/file'
  export default {
    // externalClasses:['custom-class'],//uniapp不生效
    props: {
      //默认图片
      defaultImage: {
        type: String,
        default: require('@/assets/images/error.png'),
      },
      imgHeight: {
        type: String,
        default: '128px'
      },
      imgWidth: {
        type: String,
        default: '60px'
      },
      src: String, //加载图片URL地址
    },
    data() {
      return {
        finish: false,
        imgUrl: '',
        dialogVisible: false
      }
    },
    created() {},
    computed: {},
    watch: {
      src: {
        immediate: true,
        handler(newVal) {
          if(newVal)
          this.unpdateAvatar(newVal)
        }
      }
    },
    methods: {
      handlePictureCardPreview() {
        this.dialogVisible = true;
      },
      errorImg() {
        this.imgUrl = this.defaultImage
      },
      finishLoad(e) {
        this.finish = true
      },
      async unpdateAvatar(path) {
        let res1 = await getLoadImage(path)
        const buffer = Buffer.from(res1)
        let base64 = this.arrayBufferToBase64(buffer)
        let base64Url = "data:image/png;base64," + base64
        this.imgUrl = base64Url
      },
      arrayBufferToBase64(buffer) {
        var binary = ''
        var bytes = new Uint8Array(buffer)
        var len = bytes.byteLength
        for (var i = 0; i < len; i++) {
          binary += String.fromCharCode(bytes[i])
        }
        return window.btoa(binary)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .x-image {
    cursor: pointer;
    border-radius: 10px;
    &>img {
      border-radius: 6px;
    }

    // overflow: hidden;
  }
</style>
